/**
 * @file     maximumSubarraySum.ts
 * @brief    [2461. 长度为 K 子数组中的最大和](https://leetcode.cn/problems/maximum-sum-of-distinct-subarrays-with-length-k)
 * @author   Zhu
 * @date     2024-11-21 19:32
 */

function maximumSubarraySum(nums: number[], k: number): number {
    const n = nums.length;
    let i = 0,
        sum = 0,
        max = 0;
    const cnt = Counter();

    while (i < n) {
        cnt.increase(nums[i]);
        if (i < k) {
            sum += nums[i];
        } else {
            cnt.decrease(nums[i - k]);
            sum += nums[i] - nums[i - k];
        }
        if (sum > max && cnt.size() === k) max = sum;
        i++;
    }

    function Counter() {
        const map = {};
        let size = 0;
        return {
            increase(key: number) {
                if (map[key]) map[key]++;
                else {
                    map[key] = 1;
                    size++;
                }
            },
            decrease(key: number) {
                if (map[key] === 1) {
                    delete map[key];
                    size--;
                } else map[key]--;
            },
            size() {
                return size;
            },
        };
    }

    return max;
}
